<template>
  <div class="login-container">
    <div class="login-card">
      <h2 class="login-title">非凡教育</h2>
      <el-form ref="loginForm" :model="form" :rules="rules" class="login-form">
        <el-form ref="loginForm" :model="form" :rules="rules" class="login-form">
  <el-form-item>
    <el-input
      v-model="form.username"
      placeholder="账号"
      prefix-icon="el-icon-user"
      clearable
    ></el-input>
  </el-form-item>
  <el-form-item prop="password">
    <el-input
      v-model="form.password"
      placeholder="密码"
      show-password
      :password="passwordVisible"
      prefix-icon="el-icon-lock"
      clearable
    ></el-input>
  </el-form-item>
  <el-form-item class="login-buttons">
    <el-button type="primary" @click="submitForm" class="login-button">登录</el-button>
    <el-button @click="resetForm" class="login-button">重置</el-button>
  </el-form-item>
</el-form>

      </el-form>
      <div class="login-links">
        <span class="register-link">没有账号？<a href="#" @click="showRegisterModal">注册</a></span>
        <span class="forget-password-link"><a href="#" @click.prevent="handleForgetPassword">忘记密码？</a></span>

      </div>
    </div>

<!-- 注册弹窗 -->
<el-dialog title="注册" :visible.sync="registerModalVisible" width="500px" :close-on-click-modal="false">
  <el-form :model="registerForm" :rules="registerRules" ref="registerForm" label-width="100px">
    <el-form-item label="账号" prop="username">
      <el-input v-model="registerForm.username" placeholder="请输入账号"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="registerForm.password" placeholder="请输入密码" show-password></el-input>
    </el-form-item>
    <el-form-item label="姓名" prop="name">
      <el-input v-model="registerForm.name" placeholder="请输入姓名"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="registerForm.email" placeholder="请输入邮箱"></el-input>
    </el-form-item>
    <el-form-item label="验证码" prop="verificationCode">
      <el-input v-model="registerForm.verificationCode" placeholder="请输入验证码" style="width:216.5px;"></el-input>
      <el-button @click="sendVerificationCode" :disabled="isSendingVerificationCode" style="width:141px;" class="verification-code-button">
        {{ verificationCodeButtonText }}
      </el-button>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="cancelRegister">取消</el-button>
    <el-button type="primary" @click="submitRegister">提交</el-button>
  </div>
</el-dialog>
    
    <!-- 找回密码弹窗 -->
    <el-dialog title="注册" :visible.sync="finPassword" width="500px" :close-on-click-modal="false">
  <el-form :model="findPasswordForm" :rules="finPasswordRules" ref="finPassword" label-width="100px">
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="findPasswordForm.email" placeholder="请输入邮箱"></el-input>
    </el-form-item>
    <el-form-item label="验证码" prop="verificationCode">
      <el-input v-model="findPasswordForm.verificationCode" placeholder="请输入验证码" style="width:216.5px;"></el-input>
      <el-button @click="sendPasswordCode" :disabled="isSendingVerificationCode" style="width:141px;" class="verification-code-button">
        {{ verificationCodeButtonText }}
      </el-button>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="findPasswordForm.password" placeholder="请输入密码" show-password></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="passwordEnd">
      <el-input v-model="findPasswordForm.passwordEnd" placeholder="请输入确认密码" show-password></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="cancelFindPassword">取消</el-button>
    <el-button type="primary" @click="addUser">提交</el-button>
  </div>
</el-dialog>



  </div>
</template>

<script>
export default {
  data() {
    return {

      finPassword:false,
      form: {
        username: 'cheche',
        password: '123456',
      },
      rules: {
        username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      },
      passwordVisible: false,
      loginMethod: 'username',

      // 注册相关数据
      registerModalVisible: false,
      registerForm: {
        username: '',
        password: '',
        name: '',
        email: '',
        verificationCode: '',
      },

      //找回密码相关数据
      findPasswordForm: {
        email: '',
        verificationCode: '',
        password: '',
        passwordEnd: ''
      },

      //找回密码表单验证
      finPasswordRules: {
        email:    [{ validator: this.findEmail, trigger: 'blur' }],
        verificationCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        passwordEnd:[{validator: this.passwordEndFind, trigger: 'blur' }]
      },
      registerRules: {
        
        // 注册表单验证规则
        username: [{ validator: this.username, trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        name:     [{ validator: this.name, trigger: 'blur' }],
        email:    [{ validator: this.email, trigger: 'blur' }],
        verificationCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
      },
      isSendingVerificationCode: false,
      verificationCodeButtonText: '获取验证码',
      
    };
  },
  methods: {

    // 找回密码
    addUser(){
      this.$refs.finPassword.validate(valid => {
        if (valid) {
          this.$axios({
				method: 'post',
				url: '/user/findPasswordByEmail',
				data: {
          email: this.findPasswordForm.email,
          password: this.findPasswordForm.password,
          code: this.findPasswordForm.verificationCode
				},
			}).then(res=>{
        if(res.data.flag == true){
          this.$message.success("修改成功");
          this.finPassword = false;
          this.$refs.finPassword.resetFields();
        } else{
          this.$message.warning("修改失败");
        }
      })
    } 
  });
},



    handleForgetPassword(){
      this.finPassword = true;
    },
  
    //校验密码是否一致
    passwordEndFind (rule, value, callback) {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.findPasswordForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    },


  sendResetPasswordEmail(email) {
    this.$axios
      .get('/user/sendResetPasswordEmail', {
        params: {
          email: email,
        },
      })
      .then((res) => {
        if (res.data.flag === true) {
          this.$message.success('重置密码邮件已发送，请查收邮件并重置密码');
        } else {
          this.$message.warning('发送重置密码邮件失败');
        }
      })
      .catch((error) => {
        // 处理错误
     });
  },


    //---------------------------------------------------------------------------------开始  <!-- 校验账号 -->
    username(rule, value, callback) {
    // 向后端发送请求检查账号是否存在
    const username = value;
    this.$axios
      .get('/user/getUserByLoginName', {
        params: {
          loginName: username,
        },
      })
      .then((res) => {
        // 处理返回结果
        if (res.data.data!=null) {
          // 手机号已存在，显示错误信息
          callback(new Error('账号已存在'));
        } else if(value == null || value == ''){
          callback(new Error('请输入账号')); 
          // 账号不存在，校验通过
        }else if(value.length<6){
          callback(new Error('账号长度不能小于6位')); 
        }
        else {
          callback();
        }
      })
      .catch((error) => {
        
      });
  },
    //---------------------------------------------------------------------------------结束
    //---------------------------------------------------------------------------------开始 <!-- 校验username -->
    name(rule, value, callback) {
    // 向后端发送请求检查账号是否存在
    const name = value;
    this.$axios
      .get('/user/getUserByUserName', {
        params: {
          userName: name,
        },
      })
      .then((res) => {
        // 处理返回结果
        if (res.data.data!=null) {
          // 手机号已存在，显示错误信息
          callback(new Error('名字已存在'));
        } else if(value == null || value == ''){
          callback(new Error('请输入名称')); 
          // 账号不存在，校验通过
        }else if(value.length<2){
          callback(new Error('名称长度不能小于2位')); 
        }
        else {
          callback();
        }
      })
      .catch((error) => {
        
      });
  },
    //---------------------------------------------------------------------------------结束
    
    //---------------------------------------------------------------------------------开始 <!-- 校验邮箱是否存在 -->
    email(rule, value, callback) {
    // 向后端发送请求检查账号是否存在
    const email = value;
    this.$axios
      .get('/user/getUserByEmail', {
        params: {
          email: email,
        },
      })
      .then((res) => {
        // 处理返回结果
        if (res.data.data!=null) {
          // 手机号已存在，显示错误信息
          callback(new Error('邮箱已存在'));
        } else if(value == null || value == ''){
          callback(new Error('请输入邮箱'));  
          // 账号不存在，校验通过
        }else if(value.indexOf("@") == -1){
          callback(new Error('邮箱格式不正确')); 
        }
        else {
          callback();
        }
      })
      .catch((error) => {
        
      });
  },
    //---------------------------------------------------------------------------------结束
    

   //---------------------------------------------------------------------------------开始 <!-- 找回密码，校验邮箱是否存在 -->
   findEmail(rule, value, callback) {
    // 向后端发送请求检查账号是否存在
    const email = value;
    this.$axios
      .get('/user/getUserByEmail', {
        params: {
          email: email,
        },
      })
      .then((res) => {
        // 处理返回结果
         if(value == null || value == ''){
          callback(new Error('请输入邮箱')); 
          // 账号不存在，校验通过
        }else if(value.indexOf("@") == -1){
          callback(new Error('邮箱格式不正确')); 
        }else  if (res.data.data==null) {
          callback(new Error('邮箱不存在请先注册！'));
        }
        else {
          callback();
        }
      })
      .catch((error) => {
        
      });
  },
    //---------------------------------------------------------------------------------结束
    



    //---------------------------------------------------------------------------------开始
    //登录方法
    submitForm() {
  this.$refs.loginForm.validate(valid => {
    if (valid) {
      this.$axios({
				method: 'post',
				url: '/user/login',
				data: {
					username:  this.form.username,
					password:  this.form.password,
				},
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
			}).then(res=>{
        debugger
				if(res.data.flag == true){
					window.sessionStorage.setItem('token', res.data.data.token)
          console.log(res.data.data.id)
          debugger
					window.sessionStorage.setItem('userId', res.data.data.userId)
          window.sessionStorage.setItem('userName', res.data.data.userName)
					window.sessionStorage.setItem('avatarUrl', res.data.data.avatarUrl)
          this.$router.push({path: '/HomePage'})
				} else{
        		window.sessionStorage.removeItem('token')
					this.$message.warning("账户或者密码不对");
				}
      })
    } else {
      console.log('表单验证失败');
    }
  });
},
//---------------------------------------------------------------------------------结束
    resetForm() {
      this.$refs.loginForm.resetFields();
    },
    showRegisterModal() {
      this.registerModalVisible = true;
    },
    cancelRegister() {
      this.registerModalVisible = false;
      this.$refs.registerForm.resetFields();
    },

cancelFindPassword() {
  this.finPassword = false;
  this.$refs.finPassword.resetFields();

},
    //注册
    submitRegister() {
  this.$refs.registerForm.validate((valid) => {
    if (valid) {
      // Send registration request
      this.$axios
        .post('/user/register', {
          user: {
            userName : this.registerForm.username,
            password: this.registerForm.password,
            loginName: this.registerForm.name,
            email: this.registerForm.email,
          },
          code: this.registerForm.verificationCode,
        })
        .then((res) => {
          if (res.data.flag === true) {
            this.$message.success("添加成功");
            // Clear the form
            this.registerForm = {
              username: '',
              password: '',
              name: '',
              email: '',
              verificationCode: '',
            };
            // Close the dialog
            this.registerModalVisible = false;
          } else {
            this.$message.error("添加失败");
          }
        })
        .catch((error) => {
          this.$message.error("添加失败");
        });
    } else {
      console.log('注册表单验证失败');
    }
  });
},


    //---------------------------------------------------------------------------------开始
    sendVerificationCode() {
  this.$refs.registerForm.validateField('email', (errorMessage) => {
    if (errorMessage) {
      this.$message.error(errorMessage);
    } else {
      // 发送验证码逻辑
      this.$axios
        .get('/user/sendEmail', {
          params: {
            email: this.registerForm.email,
          },
        })
        .then((res) => {
          if (res.data.flag === true) {
            this.$message.success("验证码已发送");
          } else {
            this.$message.warning("验证码发送失败");
          }
        })
        .catch((error) => {
          // 处理错误
        });

      this.isSendingVerificationCode = true;
      let count = 60;
      const timer = setInterval(() => {
        if (count > 0) {
          this.verificationCodeButtonText = `${count}秒后重新获取`;
          count--;
        } else {
          clearInterval(timer);
          this.isSendingVerificationCode = false;
          this.verificationCodeButtonText = '获取验证码';
        }
      }, 1000);
    }
  });
},

    //---------------------------------------------------------------------------------结束

    //---------------------------------------------------------------------------------开始
    //找回密码获取验证码
    sendPasswordCode() {
  this.$refs.finPassword.validateField('email', (errorMessage) => {
    if (errorMessage) {
      this.$message.error(errorMessage);
    } else {
 // 发送验证码逻辑
 this.$axios
        .get('/user/sendEmail', {
          params: {
            email: this.findPasswordForm .email,
          },
        })
        .then((res) => {
          if (res.data.flag === true) {
            this.$message.success("验证码已发送");
          } else {
            this.$message.warning("验证码发送失败");
          }
        })
        .catch((error) => {
          // 处理错误
        });

      this.isSendingVerificationCode = true;
      let count = 60;
      const timer = setInterval(() => {
        if (count > 0) {
          this.verificationCodeButtonText = `${count}秒后重新获取`;
          count--;
        } else {
          clearInterval(timer);
          this.isSendingVerificationCode = false;
          this.verificationCodeButtonText = '获取验证码';
        }
      }, 1000);
    }
  });
},
    
  },
};
</script>

<style scoped>

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-size: cover;
  background-position: center;
}

.login-card {
  width: 400px;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
  background-color: rgba(255, 255, 255, 0.9);
  animation: fade-in 0.5s ease;
}

@keyframes fade-in {
  0% {
    opacity: 0;
    transform: translateY(-20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-title {
  text-align: center;
  color: #1890ff;
  font-size: 24px;
  margin-bottom: 20px;
}

.login-form {
  margin-top: 20px;
}

.login-buttons {
  margin-top: 20px;
  text-align: center;
}

.login-links {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  color: #999;
}

.register-link,
.forget-password-link {
  font-size: 12px;
}

.register-link a,
.forget-password-link a {
  color: #1890ff;
  text-decoration: none;
}

.el-input__inner {
  border-radius: 20px;
}

.login-button {
  border-radius: 20px;
  animation: slide-in 0.5s ease;
}

@keyframes slide-in {
  0% {
    opacity: 0;
    transform: translateX(-20px);
  }
  100% {
    opacity: 1;
    transform: translateX(0);
  }
}
</style>
